import { action, makeAutoObservable, makeObservable, observable } from "mobx"
import { nanoid } from "nanoid"

export class ObservableTodoStore {
  id = ""
  task = ""
  isCompleted = false

  constructor(name: string){
    this.id = nanoid(5);
    this.task = name;
    this.isCompleted = false;

    makeObservable(this, {
      id: observable,
      task: observable,
      isCompleted: observable,
      rename: action,
      toggleDelete: action
      }
    )
  }

  rename(newName: string) {
    this.task = newName
  }

  toggleDelete() {
    this.isCompleted = !this.isCompleted;
  }
  
}


export class ObservableTodoListStore {
  todos: ObservableTodoStore[] = []

  constructor(){
    makeObservable(this, {
      todos: observable,
      addTodo: action,
      deleteTodo: action
      }
    )
  }

  get completedTasks() {
    return this.todos.filter((t) => t.isCompleted).length;
  }

  addTodo(name: string) {
    const newTodo = new ObservableTodoStore(name);
    this.todos.push(newTodo)
  }

  deleteTodo(id: string) {
    this.todos = this.todos.filter((t) => t.id !== id)
  }

}

const store = new ObservableTodoListStore();
export default store;